package com.onpositive.dataminer.core;

import com.onpositive.commons.platform.configuration.ConfigurationPersistence;
import com.onpositive.commons.platform.configuration.EclipsePreferencesConfiguration;
import com.onpositive.semantic.model.api.changes.ISetDelta;
import com.onpositive.semantic.model.api.meta.IHasMeta;
import com.onpositive.semantic.model.api.realm.IRealm;
import com.onpositive.semantic.model.api.realm.IRealmChangeListener;
import com.onpositive.semantic.model.api.realm.Realm;
import com.onpositive.semantic.model.api.realm.RealmProviderAdapter;

public class DataProviders extends RealmProviderAdapter<IDataProvider> {

	static Realm<IDataProvider> providers = new Realm<IDataProvider>();

	static {
		final DefaultUniverse instance = DefaultUniverse.getInstance();
		final EclipsePreferencesConfiguration pluginPreferences = EclipsePreferencesConfiguration
				.getPluginPreferences(Activator.getDefault());
		final DataProvidersConfiguration toLoad = new DataProvidersConfiguration();
		ConfigurationPersistence.loadObject(
				pluginPreferences.getSubConfiguration("dataProviders"), toLoad);
		for (DataProviderConfig d : toLoad.providers) {
			IDataProvider createProvider = d.createProvider();
			instance.mount(createProvider);
			providers.add(createProvider);
		}
		providers
				.addRealmChangeListener(new IRealmChangeListener<IDataProvider>() {

					@Override
					public void realmChanged(IRealm<IDataProvider> realmn,
							ISetDelta<IDataProvider> delta) {
						try {
							for (IDataProvider d : delta.getRemovedElements()) {
								toLoad.providers.remove(d.getConfig());
								instance.unmount(d);
								d.onUninstall();
								
							}
							for (IDataProvider da : delta.getAddedElements()) {
								da.onInstall();
								instance.mount(da);
								toLoad.providers.add(da.getConfig());
							}
							ConfigurationPersistence.store(
									toLoad,
									pluginPreferences
											.getSubConfiguration("dataProviders"));
							Thread s = new Thread() {
								public void run() {
									pluginPreferences.flush();
								}
							};
							s.start();
						} catch (Exception e) {
							e.printStackTrace();
							// TODO: handle exception
						}
					}
				});
	}

	@Override
	public IRealm<IDataProvider> getRealm(IHasMeta meta, Object parent) {
		return providers;
	}

}
